package com.pancm.test.wordTest;

public class HtmlStripper {

    /**
     * 去除html标签，返回纯文本内容
     *
     * @param htmlStr 待处理的HTML字符串
     * @return 纯文本内容
     */
    public static String stripHtmlTags(String htmlStr) {
        if (htmlStr == null || htmlStr.isEmpty()) {
            return htmlStr;
        }
        // 使用正则表达式匹配所有HTML标签
        return htmlStr.replaceAll("<[^>]*>", "").replaceAll("&nbsp;", " ").trim();
    }

    public static String cleanHtmlAndAddLineBreaks(String html) {
        if (html == null || html.isEmpty()) {
            return html;
        }
        String result = html.replaceAll("<[^>]+>", "");
        // 在</li>和</h1>后面添加换行符
        result = result.replaceAll("</li>", "</li>\n");
        result = result.replaceAll("</h1>", "</h1>\n");
        result = result.replaceAll("&nbsp;", " ");

        result = result.replaceAll("[ \t]+", " ");
        result = result.replaceAll("\\n+", "\n");
        result = result.trim();

        return result;
    }

    public static void main(String[] args) {
        String html = "<h1>&nbsp; &nbsp;这是一封来自新COP系统发送的邮件，请不要回复！ </h1> " +
                      "<ul> " +
                      "<li>以下待办事项请前往新COP系统(http://ncop-dev.bnq.com.cn/)，【工作台】-【我的任务】处理</li> " +
                      "<li>事件编号：&nbsp; 202007281155498785</li> " +
                      "<li>流程类型：&nbsp; 赋能自营协议创建</li> " +
                      "<li>创建时间：&nbsp; 2020-07-28 11:55:50</li> " +
                      "<li>处理时间：&nbsp; 2020-07-28 11:55:51</li> " +
                      "<li>发起人：&nbsp;&nbsp; Chao Liu 刘超</li> " +
                      "<li>部门：&nbsp;&nbsp;&nbsp; 51装饰建材/JOINERY</li> " +
                      "</ul>";

        System.out.println(html);
        String plainText = stripHtmlTags(html);
        System.out.println(plainText);
        System.out.println("=================================");
        System.out.println(cleanHtmlAndAddLineBreaks(html));
    }
}